package com.yjkf.zh.admin.controller;

import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.model.SysMenu;
import com.yjkf.zh.admin.service.SysMenuService;
import com.yjkf.zh.core.http.HttpResult;
import com.yjkf.zh.core.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @PreAuthorize("hasAuthority('sys:menu:view')")
    @PostMapping(value = "/findPage")
  //  @LogAnnotation(content = "查看菜单列表")
    public HttpResult findPage(@RequestBody PageRequest pageRequest){
        return HttpResult.ok(sysMenuService.findPage(pageRequest));
    }

    @PreAuthorize("hasAuthority('sys:menu:add') AND hasAuthority('sys:menu:edit')")
    @PostMapping(value = "/save")
    @LogAnnotation(content = "增加菜单列表")
    public HttpResult save(@RequestBody SysMenu sysMenu, HttpServletRequest request){
        Long userId = (Long)request.getSession().getAttribute("userId");
       if(userId!=1) {
           if (sysMenu.getId() != 0 && sysMenu.getId() <= 44) {
               return HttpResult.error("系统菜单不能修改！");
           }
       }
        if(userId==1) {
            return HttpResult.ok(sysMenuService.save(sysMenu));
        }
        else{
            return HttpResult.ok(sysMenuService.saveForRole(sysMenu,userId));
        }
    }

    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @PostMapping(value = "/delete")
    @LogAnnotation(content = "删除菜单列表")
    public HttpResult delete(@RequestBody List<SysMenu> records){

        return HttpResult.ok(sysMenuService.delete(records));
    }

    @PreAuthorize("hasAuthority('sys:menu:view')")
    @GetMapping(value = "/findNavTree")
    public HttpResult findNavTree(@RequestParam String userName){
        return HttpResult.ok(sysMenuService.findTree(userName,1));
    }

    @PreAuthorize("hasAuthority('sys:menu:view')")
    @GetMapping(value = "/findMenuTree")
    public HttpResult findMenuTree(){
        return HttpResult.ok(sysMenuService.findTree(null,0));
    }

    @PreAuthorize("hasAuthority('sys:menu:view')")
    @GetMapping(value = "/findMenuTree2")
    public HttpResult findMenuTree2(@RequestParam String userName){
        return HttpResult.ok(sysMenuService.findTree(userName,0));
    }


}
